﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using LoongEgg.Core;
using Microsoft.Win32;

namespace BinViewer.App
{
    public class MainViewModel : BindableObject
    {
        public BinReader BinReader { get; private set; } = new BinReader();

        public DelegateCommand OpenFileCommand { get; }
        public DelegateCommand LoadCommand { get; }

        public string Text
        {
            get { return _Text; }
            set { SetProperty(ref _Text, value); }
        }
        private string _Text;

        public string Tip
        {
            get { return _Tip; }
            set { SetProperty(ref _Tip, value); }
        }
        private string _Tip = "tip";

        public MainViewModel()
        {
            OpenFileCommand = new DelegateCommand(OpenFile);
            LoadCommand = new DelegateCommand(LoadAsync, () => BinReader.IsFileOpen && BinReader.Progress < 100);
        }

        private async void LoadAsync()
        {
            BinReader.PropertyChanged += Update_ProgressTip;
            Text = await BinReader.ReadToEndAsHexAsync().ConfigureAwait(false);
            BinReader.PropertyChanged -= Update_ProgressTip;
            Tip = "";
        }

        private void Update_ProgressTip(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Tip = $"{BinReader.Progress.ToString("00")}% loading...";
        }

        private void OpenFile()
        {
            OpenFileDialog dialog = new OpenFileDialog();

            if (dialog.ShowDialog() == true)
            {
                BinReader.Open(dialog.FileName);
                LoadCommand.RaiseCanExecuteChanged();
            }
        }
    }
}
